package cn.wolfcode.web.interceptor;

import cn.wolfcode.domain.Employee;
import cn.wolfcode.service.IPermissionService;
import cn.wolfcode.util.RequiredPermission;
import cn.wolfcode.util.UserContext;
import com.fasterxml.jackson.databind.deser.DefaultDeserializationContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.multipart.support.DefaultMultipartHttpServletRequest;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

public class CheckPermissionInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        Employee employee = UserContext.getEmployee();
        if (employee.isAdmin()){
            return true;
        }

        RequiredPermission anno = ((HandlerMethod) handler).getMethodAnnotation(RequiredPermission.class);
        if (anno==null){
            return true;
        }

        String expression = anno.expression();
//        List<String> expressions =  permissionService.queryByEmployeeId(employee.getId());
                 List<String> expressions = UserContext.getExpressions();

//        获取注解上的权限表达式，和此员工所有具有权限表达式对比，若包含放行访问
        if (expressions.contains(expression)){
            return true;
        }
        response.sendRedirect("/permission/noPermission");
//        request.getRequestDispatcher("/WEB-INF/views/common/nopermission.ftl").forward(request,response);
        return false;
    }
}
